package com.ckx;

import com.alibaba.fastjson.JSON;
import org.assertj.core.util.Lists;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenkaixiang on 2017-11-10.
 */
public class SeparateListUtils {

    /**
     * 按照容量分配list
     * @param source
     * @param capacity
     * @param <E>
     * @return
     */
    public static <E> List<List<E>> separateListByCapacity(List<E> source, int capacity) {
        List<List<E>> result = new ArrayList<>();
        int size = source.size();
        for (int i = 0; i < size / capacity; i++) {
            result.add(source.subList(i * capacity, (i + 1) * capacity));
        }
        if (size % capacity != 0) {
            result.add(source.subList(size - size % capacity, size));
        }
        return result;
    }

    /**
     * 按照份数分配list
     * @param source
     * @param n
     * @param <E>
     * @return
     */
    public static <E> List<List<E>> separateListBySize(List<E> source, int n) {
        List<List<E>> result = new ArrayList<>();
        int size = source.size();
        //(先计算出余数)
        int remainder = size % n;
        //然后是商
        int quotient = size / n;
        //偏移量
        int offset = 0;
        for (int i = 0; i < n; i++) {
            if (remainder > 0) {
                result.add(source.subList(i * quotient + offset, (i + 1) * quotient + offset + 1));
                remainder--;
                offset++;
            } else {
                result.add(source.subList(i * quotient + offset, (i + 1) * quotient + offset));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        List<List<Integer>> subLists = SeparateListUtils.separateListBySize(list, 4);
        System.out.println(JSON.toJSONString(subLists));
    }
}
